package com.alon.spring01.study;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alon.spring01.model.User;
import com.alon.spring01.model.vo.AddressVo;
import com.alon.spring01.model.vo.UserVo;
import com.alon.spring01.utils.CglibBeanCopierUtils;
import io.swagger.models.auth.In;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.Cookie;
import org.apache.ibatis.javassist.runtime.Inner;

/**
 * @program: spring01
 * @description: optional检查null
 * @author: yulongguang
 * @create: 2019-05-07 09:30
 **/
public class OptionalCheck {

    public static void main(String[] args) {
        User user = new User();
        UserVo userVo = new UserVo();
       user.setId(null);
        user.setUserName("");
        user.setPassword("");
//        user.setAge(24);
        CglibBeanCopierUtils.copyProperties(user, userVo);
        //如果传来的对象为空则赋予默认值
        //1.1 orElse不为空，为空都会运行createUser()方法
        UserVo userVo1 = Optional.ofNullable(userVo).orElse(createUser());
        System.out.println(userVo1.getUserName());
        //1.2orElseGet为空不进createUser()方法
        UserVo userVo2 = Optional.ofNullable(userVo).orElseGet(() -> createUser());
        System.out.println(userVo2.getUserName());
//        try {
//            Optional.ofNullable(userVo).orElseThrow(()->new Exception("用户不存在"));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //用map和flatMap做转换值操作
        //3、map(Function<? super T, ? extends U> mapper)和flatMap(Function<? super T, Optional<U>> mapper)
        String userName = Optional.ofNullable(userVo).map(userVo3 -> userVo3.getUserName()).get();
        System.out.println("userName:" + userName);
        //判空的骚操作
        Optional.of(new UserVo())
                .map(UserVo::getUserName)
                .ifPresent((System.out::println));

//       Optional.ofNullable(userVo).flatMap(u->u.getUserName()).get();
//        if (a.equals())
//        System.out.println(JSON.toJSONString(userVo));
        //判断对象不为空的骚操作
        Optional.ofNullable(userVo).ifPresent(u -> {
            // TODO: do something
            System.out.println("姓名：" + userVo.getUserName());
        });
        //filter-->相当于if
        try {
            Optional.ofNullable(new UserVo()).orElseThrow(() -> new Exception("用户不存在"));
            Optional<UserVo> userVo3 = Optional.ofNullable(userVo)
                                               .filter(u -> u.getUserName().length() < 6);
            System.out.println("userVo3" + userVo3.get().getUserName());

//            Optional.ofNullable(userVo).map(UserVo::getAddressVo).map(AddressVo::getAddressName)
//                    .orElseThrow(() -> new Exception("取值有错"));

            Optional.ofNullable(userVo).map(UserVo::getAddressVo).map(AddressVo::getAddressName)
                    .ifPresent(
                            u -> {
                                // TODO: do something
                            }
                    );
            //if else改写
            Optional.ofNullable(userVo).filter(u -> "1212".equals(u.getUserName()))
                    .orElseGet(() -> {
                        return new UserVo();
                    });

            String a1="12";
            Function<String, Integer> stringToInteger = (String s) -> Integer.parseInt(s);
            //使用方法引用
            Function<String, Integer> stringToInteger01 = Integer::parseInt;
            Supplier<UserVo> c1 = UserVo::new;
            UserVo s1 = c1.get();
            //等价于
            Supplier<UserVo> c2 = () -> new UserVo();
            UserVo s2 = c2.get();
            //筛选后收集到一个List中
//            List<Apple> vegetarianMenu = apples.stream().filter(Apple::isRed).collect(Collectors.toList());

//筛选加去重
            List<Integer> numbers = Arrays.asList(1,2,1,3,3,2,4);
            numbers.stream().filter(i -> i % 2 == 0).distinct().sorted().forEach(u->{
                System.out.println(u);
            });
//            Future<Double> price = CompletableFuture.supplyAsync(() -> calculatePrice(product));
            //1.1 stream()为集合创建串行流。
            //1.2 parallelStream()为集合创建并行流
            //1.3 filter过滤，相当于if
            //1.4 排序
            //1.5
            List<String> strings = Arrays.asList("abc", "", "tt", "hh", "oo", "cc");
            List<String> collect = strings.stream().filter(u -> !u.isEmpty()).sorted()
                                          .collect(Collectors.toList());

            System.out.println("strings集合：" + collect);
            //1.1forEach 遍历
            //1.2limit 获取指定数量的流
            new Random().ints().limit(10).forEach(u->{
                System.out.println(u);
            });
            List<Integer> list=Arrays.asList(10,2,6,9,4,5,7,2,6,7);
            //map 映射元素结果
            List<Integer> integers = list.stream().map(i -> i * i).distinct().sorted()
                                         .collect(Collectors.toList());
            System.out.println("list:"+integers);
            String[] strings1={"12","13"};
            Stream<String> stringStream = Arrays.asList(strings1).stream()
                                                .filter(u -> "13".equals(u)).map(u -> u.toString());

            Integer integer = Optional.ofNullable(user.getId()).map(v -> v).orElse(1);
            System.out.println("integer111:"+integer);

            SimpleDateFormat df=new SimpleDateFormat("yyyy-MM");
            String date1="2019-09";
            String date2="2020-05";
//            DateTime dateTime = DateUtil.parseDate(date1);
            Date parse = df.parse(date1);
            Date parse1=df.parse(date2);
            System.out.println(parse.getMonth()+1+12);
            System.out.println(parse1.getMonth()+1);

             Optional.ofNullable(userVo).map(UserVo::getNnnnnnn).ifPresent(u->{
                 System.out.println("uuuuuu"+u);
             });


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static UserVo createUser() {
        UserVo userVo = new UserVo();
        userVo.setUserName("zhangsan");
        return userVo;
    }

    public void setUserName() {
        UserVo userVo = new UserVo();
        userVo.setUserName("hhhhh");
    }

    public User getUser(){
        Supplier<User> supplier=User::new;
        User user = supplier.get();
        String userName="12";
        Integer integer = Integer.valueOf(userName);
        Function<String,Integer> function=Integer::valueOf;
        Integer apply = function.apply(userName);
        return supplier.get();
    }

}
